<template>
  <div>
    <vxe-card title="" class="w-full" :border="false">
      <AuForm
        ref="formRef"
        :formList="formList"
        labelWidth="100px"
        @submit="onsubmit"
      />
    </vxe-card>

    <vxe-card
      title=""
      class="w-full mt-[16px] h-[36vh]"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <div class="flex items-center">
          <span class="text-[--autata-font-color]">{{
            t("tea_infuser.dashboard.all_device.material_trend")
          }}</span>

          <!--          <el-radio-group-->
          <!--            v-model="tabActive"-->
          <!--            class="ml-2"-->
          <!--            @change="changeRadio"-->
          <!--          >-->
          <!--            <el-radio-button label="汇总" value="1" />-->
          <!--            <el-radio-button label="用料细分" value="2" />-->
          <!--            <el-radio-button label="补料细分" value="3" />-->
          <!--          </el-radio-group>-->
        </div>
        <!--        <el-link type="primary" :underline="false" @click="exportExcel('qs')"-->
        <!--          >导出-->
        <!--        </el-link>-->
      </h3>
      <div
        ref="matLineChartRef"
        v-loading="matChartLoading"
        style="width: 99%; height: calc(36vh - 56px)"
      />
    </vxe-card>

    <vxe-card
      title=""
      class="w-full mt-[16px] h-[36vh]"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <span class="text-[--autata-font-color]">{{
          t("tea_infuser.dashboard.all_device.material_scrap")
        }}</span>
        <!--        <el-link type="primary" :underline="false" @click="exportExcel('qs')"-->
        <!--          >导出-->
        <!--        </el-link>-->
      </h3>
      <div
        ref="discardChartRef"
        v-loading="discardLoading"
        style="width: 99%; height: calc(36vh - 56px)"
      />
    </vxe-card>
  </div>
</template>

<script setup lang="ts">
import { AuForm } from "@/components/AuForm";
import { computed, onMounted, ref } from "vue";
import dayjs from "dayjs";
import { storeGroupSelect } from "@/utils/formSelect";
import { deviceGetList } from "@/api/teaInfuser/device";
import { getStoreList } from "@/api/teaInfuser/store";
import { getMaterialList } from "@/api/cabinet/material";
import { useDark, useECharts } from "@pureadmin/utils";
import { cloneDeep } from "lodash-unified";
import {
  getMaterialCharts,
  getMaterialTopCharts
} from "@/api/cabinet/analysis";
import { MeasuringWeight } from "@/utils/tool";
import {
  COLOR_LIST,
  LINE_COLOR,
  TEXT_COLOR,
  THEME_COLOR
} from "@/utils/constants";
import { useI18n } from "vue-i18n";
import { pickerOptions } from "@/views/teaInfuser/dashboard/analysis/components/tools";

const { t } = useI18n();
const emit = defineEmits(["confirm"]);
// const props = defineProps({});
const { isDark } = useDark();
const theme = computed(() => (isDark.value ? "dark" : "light"));

const formRef = ref();
const formList = ref([
  {
    type: "el-date-picker",
    key: "scsj",
    inType: "datetimerange",
    label: "tea_infuser.dashboard.all_device.production_time",
    span: 12,
    rangeSeparator: "至",
    startPlaceholder: "tea_infuser.dashboard.all_device.start_time",
    endPlaceholder: "tea_infuser.dashboard.all_device.end_time",
    valueFormat: "YYYY-MM-DD HH:mm:ss",
    ...pickerOptions(formRef),
    defaultValue: [
      dayjs().subtract(10, "day").format("YYYY-MM-DD HH:mm:ss"),
      dayjs().format("YYYY-MM-DD HH:mm:ss")
    ]
  },
  () => storeGroupSelect("group_idlist", {}, true),
  {
    type: "select",
    key: "store_id",
    label: "tea_infuser.dashboard.all_device.store_name",
    placeholder: "tea_infuser.dashboard.all_device.store_name_placeholder",
    valueKey: "id",
    labelKey: "name",
    filterable: true,
    options: []
  }
]);

const tabActive = ref("1");
const matChartLoading = ref(false);
const matLineChartRef = ref();
const { setOptions: setMatLineOptions } = useECharts(matLineChartRef, {
  theme
});

const matTopBarLoading = ref(false);
const matTopBarChartRef = ref();
const { setOptions: setMatBarOptions } = useECharts(matTopBarChartRef, {
  theme
});

const discardLoading = ref(false);
const discardChartRef = ref();
const { setOptions: setDiscardBarOptions } = useECharts(discardChartRef, {
  theme
});
const matPieChartRef = ref();
const { setOptions: setMatPieOptions } = useECharts(matPieChartRef, {
  theme
});

const exportExcel = {
  qs: () => {}
};

const getSearchData = () => {
  const param = cloneDeep(formRef.value.getFormData());

  const groupObjArr = [];
  if (param.group_idlist != undefined && param.group_idlist.length > 0) {
    for (const item of param.group_idlist) {
      groupObjArr.push({ group_id: item });
    }
    param["group_idlist"] = JSON.stringify(groupObjArr);
  }

  param["create_start_time"] = param.scsj[0];
  param["create_end_time"] = param.scsj[1];
  param.size = 0;
  param.start_page = 0;
  param["device_type"] = "";

  delete param["scsj"];
  return param;
};

// region  物料数据趋势图

/**
 * 获取状态
 */
const getStatus = () => {
  let param;
  if (tabActive.value === "1") {
    // 汇总
    param = {
      groupname: "status"
    };
  } else if (tabActive.value === "2") {
    // 用料
    const statusArray = [
      { status: 1 },
      { status: 2 },
      { status: 4 },
      { status: 5 },
      { status: 6 }
    ];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  } else if (tabActive.value === "3") {
    // 补料
    const statusArray = [{ status: 3 }];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  } else if (tabActive.value === "4") {
    // 报废
    const statusArray = [{ status: 2 }, { status: 5 }, { status: 6 }];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  } else if (tabActive.value === "5") {
    // 校准
    const statusArray = [{ status: 4 }];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  }

  return param;
};

/**
 * 获取最大值和单位
 * @param list
 */
const getMaxAndUnit = (
  list: any[]
): {
  maxNum: number;
  weightUnit: "g" | "kg" | "ton";
  weightText: string;
} => {
  //得出最大值
  const liveDataNum = [];
  list.forEach((item, i) => {
    if (!isNaN(item.normal_num)) {
      liveDataNum.push(item.normal_num);
    }
    if (!isNaN(item.waste_num)) {
      liveDataNum.push(item.waste_num);
    }
    if (!isNaN(item.calibration_num)) {
      liveDataNum.push(item.calibration_num);
    }
    if (!isNaN(item.cancle_num)) {
      liveDataNum.push(item.cancle_num);
    }
    if (!isNaN(item.unusual_num)) {
      liveDataNum.push(item.unusual_num);
    }
    if (!isNaN(item.repair_num)) {
      liveDataNum.push(item.repair_num);
    }
    if (!isNaN(item.num)) {
      liveDataNum.push(item.num);
    }
  });
  let maxNum = 0;
  if (liveDataNum.length > 0) {
    maxNum = liveDataNum.reduce((max, current) => {
      return Math.max(max, current);
    });
  }
  let weightUnit: "g" | "kg" | "ton" = "ton";
  let weightText = "";
  //根据最大值得出换算的单位
  if (maxNum >= 1000000) {
    weightUnit = "ton";
    weightText = "吨";
  } else if (maxNum >= 1000) {
    weightUnit = "kg";
    weightText = "kg";
  } else {
    weightUnit = "g";
    weightText = "g";
  }

  return {
    maxNum,
    weightUnit,
    weightText
  };
};

/**
 * 设置折线图数据
 * @param xArr
 * @param allArr
 */
const setLineOptionData = (
  xArr: string[],
  allArr: { [key: string]: any[] }
) => {
  const series = [];
  let index = 0;
  for (const allArrKey in allArr) {
    series.push({
      data: allArr[allArrKey],
      type: "line",
      name: allArrKey,
      showSymbol: false,
      lineStyle: {
        color: COLOR_LIST[index]
      }
    });
    index++;
  }

  setMatLineOptions({
    title: {
      show: false
    },
    grid: {
      left: "2%",
      right: "2%",
      bottom: "6%",
      top: "6%",
      containLabel: true
    },
    color: COLOR_LIST,
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross"
      }
    },
    xAxis: {
      type: "category",
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    series
  });
};

const setDiscardData = async (xArr: string[], allArr: any[]) => {
  setDiscardBarOptions({
    title: {
      show: false
    },
    grid: {
      left: "2%",
      right: "2%",
      bottom: "6%",
      top: "6%",
      containLabel: true
    },
    color: COLOR_LIST,
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross"
      }
    },
    xAxis: {
      type: "category",
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    series: [
      {
        data: allArr,
        type: "bar",
        name: t("tea_infuser.dashboard.all_device.scrap_amount"),
        barMaxWidth: 30,
        itemStyle: {
          color: COLOR_LIST[0]
        }
      }
    ]
  });
};

const setAllData = (list: any[], xArr) => {
  const { weightUnit } = getMaxAndUnit(list);

  // 用料
  const useArr = list.map(item => {
    const num =
      item.normal_num +
      item.waste_num +
      item.calibration_num +
      item.cancle_num +
      item.unusual_num;

    return Number(MeasuringWeight(weightUnit, num));
  });

  // 报废
  const scrapArr = list.map(item =>
    Number(MeasuringWeight(weightUnit, item.cancle_num + item.unusual_num))
  );

  setLineOptionData(xArr, {
    [t("tea_infuser.dashboard.all_device.material_usage")]: useArr
  });
  setDiscardData(xArr, scrapArr);
};

const setMaterialData = (list: any[], xArr: string[]) => {
  const dataObj: { [key: string]: any[] } = {};
  for (const item of list) {
    const key = item.material_name;
    if (dataObj[key] === undefined) {
      dataObj[key] = [];
    }
    dataObj[key].push(item.num);
  }
  xArr = [...new Set(xArr)];
  console.log(dataObj);
  setLineOptionData(xArr, dataObj);
};

const getMatLineChart = async () => {
  const param = getSearchData();
  param["grouptime"] = "day";
  const statusParam = getStatus();
  try {
    const res = await getMaterialCharts({ ...param, ...statusParam });
    console.log(res);
    const list = res.data.reverse();
    const xArr = list.map(item => item.time);
    if (tabActive.value === "1") {
      setAllData(list, xArr);
    } else {
      setMaterialData(list, xArr);
    }
  } catch (e) {}
};

const changeRadio = () => {
  getMatLineChart();
};

// endregion

// region 物料top5分布
const setTopOptionData = (xArr: string[], yArr: string[]) => {
  setMatBarOptions({
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "value",
      boundaryGap: [0, 0.01],
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    yAxis: {
      type: "category",
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
    },
    series: [
      {
        name: t("tea_infuser.dashboard.all_device.total_amount"),
        type: "bar",
        data: yArr,
        itemStyle: {
          color: COLOR_LIST[0]
        }
      }
    ]
  });
};

const setTopPieOptionData = (data: any[]) => {
  setMatPieOptions({
    tooltip: {
      trigger: "item"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    series: [
      {
        name: t("tea_infuser.dashboard.all_device.ranking_ratio"),
        type: "pie",
        radius: "70%",
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  });
};

const getMatTopCharts = async () => {
  const param = getSearchData();
  param["grouptime"] = "day";
  const statusParam = getStatus();
  try {
    const res = await getMaterialTopCharts({ ...param, ...statusParam });
    console.log(res);
    const list = res.data;
    const xArr = list.map(item => item.material_name);
    const yArr = list.map(item => item.num).sort((a, b) => b - a);
    setTopOptionData(xArr, yArr);

    const pieData = list.map((v, i) => {
      return {
        value: v.num,
        name: v.material_name,
        itemStyle: {
          color: COLOR_LIST[i]
        }
      };
    });
    setTopPieOptionData(pieData);
  } catch (e) {}
};
// endregion

const init = () => {
  deviceGetList({
    size: 0
  }).then(res => {
    formRef.value.setFormProps("device_id", {
      options: res.data
    });
  });

  getStoreList({
    size: 0
  }).then(res => {
    formRef.value.setFormProps("store_id", {
      options: res.data
    });
  });

  getMaterialList({
    size: 0
  }).then(res => {
    formRef.value.setFormProps("material_id", {
      options: res.data
    });
  });

  getMatLineChart();
  getMatTopCharts();
};

const onsubmit = () => {
  getMatLineChart();
  getMatTopCharts();
};

onMounted(() => {
  init();
});
</script>
